package com.gams.springboot.controller;

import com.gams.springboot.pojo.Role;
import com.gams.springboot.pojo.User;
import com.gams.springboot.services.RoleService;
import com.gams.springboot.services.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;

/**
 * @author tql
 * @current springboot
 * @create 2021-09-2-11:33
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @RequestMapping(value = "/user",method = RequestMethod.GET )
    @ResponseBody
    public Object queryUser(@RequestParam(value="page") int page,
                            @RequestParam(value="limit") int limit){
        HashMap<String, Object> map = new HashMap<>();
        PageInfo pageInfo = userService.findAllUser(page,limit);
        map.put("code",0);
        map.put("msg","加载成功");
        map.put("count",pageInfo.getTotal());
        map.put("data",pageInfo.getList());
        return map;
    }

    @RequestMapping("/login")
    public ModelAndView login(){
        ModelAndView v = new ModelAndView("/page/login-1.html");
        return v;
    }
    @RequestMapping("/list")
    public ModelAndView list(){
        ModelAndView v = new ModelAndView("/page/userlist.html");
        return v;
    }

    @RequestMapping("/edit")
    public ModelAndView edit(@RequestParam(value = "id")int id,
                             @RequestParam(value = "name")String name,
                             @RequestParam(value = "account")String account,
                             @RequestParam(value = "status")String status
                             ){
        ModelAndView v = new ModelAndView("/page/table/edit.html");
        v.addObject("id" ,id);
        v.addObject("name",name);
        v.addObject("account",account);
        v.addObject("status",status);
        v.addObject("roleEditList",roleService.selectAllRole());
        v.addObject("roleIdList",userService.selectRoleIdByUserId(id));
        return v;
    }

    @RequestMapping("/welcome")
    public ModelAndView welcome(){
        ModelAndView v = new ModelAndView("/page/welcome.html");
        return v;
    }


    @PostMapping("/addUser")
    @ResponseBody
    public int addUser(@RequestBody  User user,
                       @RequestParam(value="rolelist") List<Long> rolelist){
         long id =0;
         int  result = 0;
         if(userService.addUser(user)){
              id = userService.queryId(user.getName());
             for(Long s : rolelist){
                 result = userService.insertUserRole(id,s);
             }
         }
        return  result;
    }

    @PostMapping("/updateUser")
    @ResponseBody
    public int updateUser(@RequestBody  User user,
                          @RequestParam(value = "roleId") List<Long> roleId,
                          @RequestParam(value = "userId") String userId){
        int result = 0;
        long id =Integer.parseInt(userId);
        if( userService.updateUser(user)>0){
           if( userService.deleteUserRoleById(id)>0){
               for(Long s : roleId){
                   result =  userService.insertUserRole(id,s);
               }
           }
        }
        return result;
    }

    @PostMapping("/deleteUser")
    @ResponseBody
    public int deleteUser(String id){
        long id1 = Integer.parseInt(id);
        int result = userService.deleteUser(id1);
        return result;
    }

    @PostMapping("/deleteSelectedUser")
    @ResponseBody
    public int deleteSelectedUser(@RequestParam(value="selectedList") String[] selectedList){
        long[] intTemp = new long[selectedList.length];
        for (int i = 0; i <selectedList.length; i++)
        {
            intTemp[i] = Integer.parseInt(selectedList[i]);
        }
        int result = 0;
        for(Long s : intTemp){
            result = userService.deleteUser(s);
        }
        return result;
    }


    @RequestMapping("/reset")
    @ResponseBody
    public ModelAndView reset(@RequestParam(value="selectlist") String[] selectList){
    ModelAndView v = new ModelAndView("/page/table/reset.html");
    v.addObject("selectList",selectList);
        return v;
    }

    @RequestMapping("/resetUserPassword")
    @ResponseBody
    public int resetUserPassword(@RequestParam(value="password") String password,
                                 @RequestParam(value="list") String[] selectedList){
        long[] intTemp = new long[selectedList.length];
        for (int i = 0; i <selectedList.length; i++)
        {
            intTemp[i] = Integer.parseInt(selectedList[i]);
        }
        int result = 0;
        for(Long s : intTemp){
            result =userService.updateUserPassword(password,s);
        }
        return result;
    }

    @RequestMapping("/searchUser")
    @ResponseBody
    public Object searchUser(@RequestParam(value = "name") String name,
                                 @RequestParam(value = "account") String account,
                                 @RequestParam(value = "status") String status,
                                 @RequestParam(value="page") int page,
                                 @RequestParam(value="limit") int limit){
        HashMap<String, Object> map = new HashMap<>();
        PageHelper.startPage(page,limit);
        //获取用户列表
        List<User> user = userService.searchUser(name,account,status);
        //加载到分页信息类里面
        PageInfo<User>  pageInfo = new PageInfo( user);
        map.put("code",0);
        map.put("msg","加载成功");
        map.put("count",pageInfo.getTotal());
        map.put("data",pageInfo.getList());
        return map ;
    }


    @RequestMapping("/loginSubmit")
    @ResponseBody
    public ModelAndView loginSubmit(String name,String password) {
        ModelAndView v = new ModelAndView("/index");
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(name,password);
        //执行登录方法
        try {
            subject.login(token);
        }catch (UnknownAccountException e){
            v.addObject("msg","用户名错误");
            v.setViewName("/page/404.html");
        }catch (IncorrectCredentialsException e){
           v.addObject("msg","密码错误");
            v.setViewName("/page/404.html");

        }
        return v;
    }

    @RequestMapping("/noauth")
    @ResponseBody
    public ModelAndView noAuth(){
        return new ModelAndView("/page/404.html");
    }
}
